<?php


use Biz\service\brand\BlindBox;
use Biz\service\brand\BlindBoxLottery;

class RandPrizeAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_NOTHING;

    public function main()
    {
        $uid = $this->getRequest()->getQuery('uid', 0);
        $fans = $this->getRequest()->getQuery('fans', 0);
        $type = $this->getRequest()->getQuery('type', 0);
        $quality = $this->getRequest()->getQuery('quality', 0);
        $result = [];
        if ($uid) {
            //UserCounter::hSet(UserCounter::addPrefix($uid), UserCounter::TYPE_FANS, $fans);
            $prizeList = BlindBox::getPrizeList($uid, true);
            $prizeLotteryPriceArr = BlindBoxLottery::getPrizeLotteryPrice($prizeList);
            $userLevelId = $this->getUserBoxLevel($fans, $type, $quality);//查询用户的中奖级别
            //查询奖品的中奖权重
            $randMax = BlindBoxLottery::RAND_MAX;
            $prizeWeightArr = BlindBoxLottery::getPrizeWeight($uid, $prizeLotteryPriceArr, $userLevelId, $randMax);
            //根据权重获取中奖奖品id
            $lotteryPrizeId = BlindBoxLottery::getRandPrizeId($prizeWeightArr, $randMax);
            $result = $prizeList[$lotteryPrizeId];
        }
        $result['uid'] = $uid;
        $result['fans'] = $fans;
        $result['type'] = $type;
        $this->setSuccess($result);
    }

    function getUserBoxLevel($fans, $type = 0, $quality = 0)
    {
        $userLevelId = 0;
        foreach (BlindBoxLottery::USER_BLIND_LEVEL as $id => $row) {
            $fansFlag = false;
            $userTypeFlag = false;
            if ($row['fans']) {
                if ($fans >= $row['fans']['min'] && $fans <= $row['fans']['max']) {
                    $fansFlag = true;
                }
            } else {
                $fansFlag = true;
            }
            if ($row['user_type']) {
                if (in_array($type, $row['user_type']['type']) || in_array($quality, $row['user_type']['auth_tag'])
                    || in_array($quality, $row['user_type']['quality']) || in_array($quality, $row['user_type']['quality2'])) {
                    $userTypeFlag = true;
                }
            } else {
                $userTypeFlag = true;
            }
            if ($fansFlag && $userTypeFlag) {
                $userLevelId = $id;
                break;
            }
        }
        return $userLevelId;
    }
}